package com.ncloud.crm.dubboservice.impl;

import java.util.List;
import java.util.Map;

import com.ncloud.crm.service.impl.OrderFinishServiceImpl;
import com.ncloud.crm.utils.OrderNodeDefineUtils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.business.OrderInfoBusi;
import com.ncloud.crm.dubboservice.OrderDubboService;
import com.ncloud.crm.service.OrderService;

@Service(retries = -1,delay = -1)
public class OrderDubboServiceImpl implements OrderDubboService {
	private static final Logger logger = LogManager.getLogger(OrderDubboServiceImpl.class);
	@Autowired
	private OrderService orderservice;
	@Autowired
	private OrderInfoBusi orderInfoBusi;
	@Autowired
	private OrderFinishServiceImpl finishService;
	@Override
	public Object getMyOrder(JSONObject json) {
		Object orders = orderservice.getOrderList(json);
		return orders;
	}
	
	@Override
	public Object getAllOrderList(JSONObject json){
		Object object=orderservice.getAllOrderList(json);
		return object;
	}
	
	@Override
	public JSONObject receiveOrderInfo(JSONObject json) {
		JSONObject resultJson = new JSONObject();
		JSONObject setParam = new JSONObject();
		logger.debug("接收订单集合信息："+json.toJSONString());
		if(json.containsKey("userID")){
			json.put("userId",json.getLong("userID"));
		}
		JSONObject orderInfos = orderInfoBusi.orderValidateInfo(json,setParam);
		orderInfoBusi.orderInfoGene(orderInfos);
		if(orderInfos.containsKey("ORDER")){
			Long orderId = orderInfos.getJSONObject("ORDER").getLong("orderId");
			Long result = orderservice.getOrderNoWorkInfo(orderId);
			if(result != null){
				finishService.finishOrder(result);
			}
			//返回订单id
			resultJson.put("orderId",String.valueOf(orderId));
		}

		return resultJson;
	}

	/*收费页面确定费用后，正式提交调用方法，主要处理订单和工单状态*/
	@Override
	public void processOrder(JSONObject json) {
		orderInfoBusi.stateInfoUpdate(json);
	}

	@Override
	public JSONObject completeOrder(JSONObject json) {
		if(!json.containsKey("orderId"))
			throw new UserException(ResultEnum.PARAM_ERROR);
		if(!json.containsKey(OrderNodeDefineUtils.ORDER_ITEM)
			|| json.getJSONObject(OrderNodeDefineUtils.ORDER_ITEM).isEmpty())
			throw new UserException(ResultEnum.PARAM_ERROR);
		JSONObject jsonObject = orderInfoBusi.completeOrder(json);
		return jsonObject;
	}

	@Override
	public JSONArray getNeedConstructOrders(JSONObject json) {
		List<Map<String, Object>> orders = orderservice.getNeedConstructOrders();
		return JSON.parseArray(JSON.toJSONString(orders));
	}
}
